// pages/lead-coupons/lead-coupons.js
var app = getApp(), api = getApp().api;
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');

// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'R24BZ-NFDHJ-X3UFS-FBJPQ-AKQOT-JOBND' // 必填
});
var areaInfo = [];//所有省市区县数据
var provinces = [];//省
var citys = [];//城市
var countys = [];//区县
var index = [0, 0, 0];
var cellId;
var t = 0;
var show = false;
var moveY = 200;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    allSelect: "circle",
    num: 0,
    count: 0,
    province: '',
    city: '',
    district: '',
    latitude: '',
    longitude: '',
    addressShow: false,
    value: [0, 0, 0],
    provinces: provinces,
    citys: citys,
    countys: countys,
  },
  getrr(e){
    let vm = this;
    vm.setData({
      ceshi:444
    })
  },
  //改变选框状态
  change: function (e) {
    var that = this
    //得到下标
    var index = e.currentTarget.dataset.index
    //得到选中状态
    var select = e.currentTarget.dataset.select

    if (select == "circle") {
      var stype = "success"
    } else {
      var stype = "circle"
    }

    //把新的值给新的数组
    var newList = that.data.list
    newList[index].select = stype
    //把新的数组传给前台
    that.setData({
      list: newList
    })
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count()
  },
  //加法
  addtion: function (e) {
    var that = this
    //得到下标
    var index = e.currentTarget.dataset.index
    console.log(index, 4545)
    //得到点击的值
    var num = e.currentTarget.dataset.num
    //默认99件最多
    if (num < 5) {
      num++
    }
    //把新的值给新的数组
    var newList = that.data.list
    newList[index].num = num

    //把新的数组传给前台
    that.setData({
      list: newList
    })
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count()
  },
  //减法
  subtraction: function (e) {
    var that = this
    //得到下标
    var index = e.currentTarget.dataset.index
    //得到点击的值
    var num = e.currentTarget.dataset.num
    //把新的值给新的数组
    var newList = that.data.list
    //当1件时，点击移除
    // if (num == 1) {
    //   newList.splice(index, 1)
    // } else {
    //   num--
    //   newList[index].num = num
    // }
    if (num > 1) {
      num--
      newList[index].num = num
    }

    //把新的数组传给前台
    that.setData({
      list: newList
    })
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count()
  },
  //全选
  allSelect: function (e) {
    var that = this
    //先判断现在选中没
    var allSelect = e.currentTarget.dataset.select
    var newList = that.data.list
    if (allSelect == "circle") {
      //先把数组遍历一遍，然后改掉select值
      for (var i = 0; i < newList.length; i++) {
        newList[i].select = "success"
      }
      var select = "success"
    } else {
      for (var i = 0; i < newList.length; i++) {
        newList[i].select = "circle"
      }
      var select = "circle"
    }
    that.setData({
      list: newList,
      allSelect: select
    })
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count()
  },
  //计算数量
  countNum: function () {
    var that = this
    //遍历数组，把既选中的num加起来
    var newList = that.data.list
    var allNum = 0
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].select == "success") {
        allNum += parseInt(newList[i].num)
      }
    }
    parseInt
    console.log(allNum)
    that.setData({
      num: allNum
    })
  },
  //计算金额方法
  count: function () {
    var that = this
    //思路和上面一致
    //选中的订单，数量*价格加起来
    var newList = that.data.list
    var newCount = 0
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].select == "success") {
        newCount += newList[i].num * newList[i].sub_price
      }
    }
    that.setData({
      count: newCount
    })
  },
  cartclose(e){
    getApp().core.redirectTo({
      url: "/pages/order/order?status=1"
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    getProvinceData(this)
  },
  getProvince()
  {
   
  },
  getcity($provinceid){
    var that= this;
    getApp().request({
      url: getApp().api.user.getcity,
      data: {
      parent_id:2
      },
      success: function (e) {
        console.log(e,787878);
        that.setData({
          citys:e.data
        })
      
      }
    })
  },
  getdistrict() {
    var that = this;
    getApp().request({
      url: getApp().api.user.getdistrict,
      data: {
        parent_id: 3,
      },
      success: function (e) {
        console.log(e, 787878);
        that.setData({
          districes: e.data
        })

      }
    })
  },
  getlists() {
    var that = this;
    console.log(that, 4343434);
    var province = that.data.province;
    var city = that.data.city;
    var district = that.data.district;
    console.log(province, city, 3434343);
    getApp().request({
      url: getApp().api.user.coupons,
      data: {
        province: province,
        city: city,
        district: district,
      },
      success: function (e) {
        that.setData({
          list: e.data
        })
        console.log(e, 99999);
      },
      complete: function () {
        getApp().core.hideLoading();
      }
    });

  },
getlist()
{
  var that = this;
  console.log(that,4343434);
  var province = that.data.province;
   var city = that.data.city;
   var district = that.data.district;
  console.log(province,city,3434343);
  getApp().request({
    url: getApp().api.user.coupons,
    data: {
      province: '',
      city: '',
      district: '',
    },
    success: function (e) {
      that.setData({
        list:e.data
      })
      console.log(e, 99999);
    },
    complete: function () {
      getApp().core.hideLoading();
    }
  });

},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    }
    )
  },
  //移动按钮点击事件
  translate: function (e) {

    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    this.setData({
      addressShow: true
    })
    // this.animation.translate(arr[0], arr[1]).step();
    // animationEvents(this, moveY, show);

  },
  //隐藏弹窗浮层
  hiddenFloatView(e) {
    // console.log(e);
    // moveY = 200;
    // show = true;
    // t = 0;
    // animationEvents(this, moveY, show);
    this.setData({
      addressShow: false
    })

  },
  hiddenFloatViewsure(e) {
    console.log(e);
    // moveY = 200;
    // show = true;
    // t = 0;
    // animationEvents(this, moveY, show);
    this.setData({
      addressShow: false
    })
    var that = this;
    var val = that.data.value;
    console.log(val)
    this.setData({
      // address: that.data.provinces[val[0]].provinceName + that.data.citys[val[1]].cityName + that.data.countys[val[2]].countyName,
      province: that.data.provinces[val[0]].name,
      city: that.data.citys[val[1]].name,
      district: that.data.countys[val[2]].name,
      provinceid: that.data.provinces[val[0]].id,
      cityid: that.data.citys[val[1]].id,
      countyid: that.data.countys[val[2]].id
    }),
      setTimeout(function () {
       that.getlists();
      }, 500)
 
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let vm = this;
    vm.getUserLocation();
  },
  getlat(e){
    let vm = this;
    vm.getUserLocation();
  },
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res,7878)
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(res,999);
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        let district = res.result.ad_info.district
        vm.setData({
          province: province,
          city: city,
          district:district,
          latitude: latitude,
          longitude: longitude
        })
        vm.getlist();

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  // 选择地址
  //滑动事件
  bindChange: function (e) {
    var that = this;
    var val = e.detail.value
    console.log(val[0])
    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      console.log(that.data.provinces[val[0]].provinceCode)
      getCityArr(val[0], that.data.provinces[val[0]].id, this);//获取地级市数据
      console.log(that.data.citys[val[1]].cityCode)

    } else {    //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        getCountyInfo(val[0], val[1], val[2], that.data.citys[val[1]].id, this);//获取区县数据
      }
    }
    index = val;

    console.log(index + " => " + val);

    //更新数据
    this.setData({
      value: [val[0], val[1], val[2]],
      // provinceName: that.data.provinces[val[0]].provinceName,
      // cityName: that.data.citys[val[1]].cityName,
      // countyName: that.data.countys[val[2]].countyName,
      // provinceCode: that.data.provinces[val[0]].provinceCode,
      // cityCode: that.data.citys[val[1]].cityCode,
      // countyCode: that.data.countys[val[2]].countyCode
    })

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  cartSubmit:function(e)
  {
    var that= this;
    var t = getApp().getUser();
   
    var list = that.data.list;
    var sellist = [];
    var count = that.data.count;
    console.log(e, 8888,list,999)
    if (count==0){
      console.log(1212)
      getApp().core.showModal({
        title: "提示",
        content: '请选择优惠卷',
        showCancel: !1,
        success: function (e) {
        }
      });
    }else{
      for (var i = 0; i < list.length; i++) {
        if (list[i].select == 'success') {
          sellist.push(list[i])
        }
      }
      console.log(sellist, count, 777)
      getApp().request({
        url: getApp().api.user.getcoupons,
        data: {
          sellist: sellist,
          count: count,
          userid: t.id,

        },
        success: function (e) {
          if (e.code == 4) {
            getApp().core.showModal({
              title: "提示",
              content: '优惠券数量不够请重新选择',
              showCancel: !1,
              success: function (e) {

              }
            });
          }
          if (e.code == 5) {
            getApp().core.showModal({
              title: "提示",
              content: '优惠券数量领取过多，请重新选择',
              showCancel: !1,
              success: function (e) {
                e.confirm && getApp().core.redirectTo({
                  url: "pages/lead-coupons/lead-coupons"
                });

              }
            });
          }
          if (e.code == 0) {
            getApp().core.showModal({
              title: "提示",
              content: '优惠券领取成功',
              showCancel: !1,
              success: function (e) {
                e.confirm && getApp().core.redirectTo({
                  url: "/pages/user-coupon/user-coupon"
                });

              }
            });

          }
          console.log(e, 99999);
        },
        complete: function () {
          getApp().core.hideLoading();
        }
      });
    }
    
    
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
//动画事件
function animationEvents(that, moveY, show) {
  console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 0,
    timingFunction: "ease",
    delay: 0
  }
  )
  that.animation.translateY(moveY + 'vh').step()

  that.setData({
    animation: that.animation.export(),
    show: show
  })

}
//获取省份数据
function getProvinceData(that) {
  getApp().request({
    url: getApp().api.user.getprovince,
    data: {

    },
    success: function (e) {
      console.log(e, 787878);
      that.setData({
        provinces: e.data
      })
      //初始化调一次可更改
      getCityArr(0, e.data[0].id, that);
      getCountyInfo(0, 0, 0, "110000", that);
    }
  })



}

// 获取地级市数据
function getCityArr(count, res, that) {
  getApp().request({
    url: getApp().api.user.getcity,
    data: {
      parent_id: res
    },
    success: function (e) {
      console.log(e, 787878);
      that.setData({
        citys: e.data,
        value: [count, 0, 0],
      })
      getCountyInfo(count, 0, 0, e.data[0].id, that);//获取区县数据
    }
  })
  
}

// 获取区县数据
function getCountyInfo(column0, column1, column2, res, that) {
  getApp().request({
    url: getApp().api.user.getdistrict,
    data: {
      parent_id: res,
    },
    success: function (e) {
      if (e.data == '') {
        that.setData({
          countys: [],
          value: [column0, column1, column2],
          // countyCode: '',
          // countyName:''
        })

      } else {
        that.setData({
          countys: e.data,
          value: [column0, column1, column2],
          // countysid: resu.data.data[0].id,
          // countyCode: resu.data.data[0].countyCode,
          // countyName: resu.data.data[column2].countyName,
        })
      }

    }
  })

  

}